namespace Spotted.Storage.Tables.ViewModels
{
    using System;
    using System.Windows;
    using System.Windows.Navigation;
    using System.Windows.Threading;
    using Microsoft.WindowsAzure.Samples.Phone.Storage;

    public class SampleDataTablePageViewModel : TableBaseViewModel<SampleData>
    {
        private readonly ICloudTableClient cloudTableClient;

        private static bool sampleDataTableCreated;

        public SampleDataTablePageViewModel()
            : this(CloudStorageContext.Current.Resolver, Deployment.Current.Dispatcher)
        {
        }

        public SampleDataTablePageViewModel(ICloudStorageClientResolver resolver, Dispatcher dispatcher)
            : base(resolver.ResolveTableServiceContext("SampleData"), dispatcher)
        {
            this.cloudTableClient = resolver.CreateCloudTableClient();
        }

        public event EventHandler<NavigationEventArgs> Navigate;

        public ICloudTableClient CloudTableClient
        {
            get
            {
                return this.cloudTableClient;
            }
        }

        public override string TableName
        {
            get { return "SampleData"; }
        }

        public override void LoadTable()
        {
            if (!this.IsLoading)
            {
                if (!sampleDataTableCreated)
                {
                    try
                    {
                        this.cloudTableClient.CreateTableIfNotExist(this.TableName, this.OnCreateTable);
                    }
                    catch (Exception exception)
                    {
                        this.IsLoading = false;
                        this.Message = string.Concat("Error: ", exception.Message);
                    }
                }
                else
                {
                    base.LoadTable();
                }
            }
        }

        public void NavigateTo(Uri navigationUri)
        {
            this.RaiseNavigate(navigationUri);
        }

        private void OnCreateTable(CloudOperationResponse<bool> response)
        {
            if (response.Success)
            {
                base.LoadTable();
                sampleDataTableCreated = true;
            }
            else
            {
                this.Message = string.Concat("Error: ", response.ErrorMessage);
            }
        }

        private void RaiseNavigate(Uri uri)
        {
            var navigate = this.Navigate;
            if (navigate != null)
            {
                navigate(this, new NavigationEventArgs(null, uri));
            }
        }
    }
}
